/*
 * @Description: 表单校验
 * @Author: chenju
 * @Date: 2021-11-15 09:53:21
 * @LastEditors: qingyang
 * @LastEditTime: 2022-05-23 13:53:19
 */

// 金额校验
export const amtValidator = () => {
  return {
    type: 'string',
    pattern: /(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{1,2}$)|(^0$)/,
    message: '请输入正确的金额格式（最小精确到分）',
    trigger: ['blur', 'change', 'submit']
  };
};

// 百分比校验
export const percentValidator = () => {
  return {
    type: 'string',
    pattern: /(^(\d{1,2})(\.\d{0,2})?$)|(^100$)|(^100.0$)|(^100.00$)/,
    message: '请输入正确的格式（最多保留两位小数）',
    trigger: ['blur', 'change', 'submit']
  };
};

// 手机号校验
export const mobileValidator = () => {
  return {
    type: 'string',
    pattern: /^1[0123456789]\d{9}$/,
    message: '请输入正确的手机号格式',
    trigger: ['blur', 'change', 'submit']
  };
};

// 邮箱校验
export const emailValidator = () => {
  return {
    type: 'string',
    pattern: /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/,
    message: '请输入正确的邮箱格式',
    trigger: ['blur', 'change', 'submit']
  };
};

/**
 * 数字校验
 * @param digit 位数
 * @param canZero 能否为0
 * @param canNegative 能否为负数
 * @returns
 */
export const numberValidator = (digit?: number, canZero = true, canNegative = false) => {
  let reg = `(^${canNegative ? '[+-]?' : ''}[1-9]{1}[0-9]*$)`;
  let msg = '请输入正确的数字';
  if (digit) {
    reg += `|(^${canNegative ? '[+-]?' : ''}[0-9]*\\.[0-9]{1,${digit}}$)`;
    msg += `(${canZero ? '' : '不含0，'}最多保留${digit}位小数${canNegative ? '' : '，非负数'})`;
  } else {
    msg += `(${canZero ? '' : '不含0'}${canNegative ? '' : '，非负数'})`;
  }
  if (canZero) {
    reg += '|(^0$)';
  }
  console.log('reg', reg, msg);
  return {
    pattern: new RegExp(reg),
    message: msg,
    trigger: ['blur', 'change', 'submit']
  };
};
